package cn.nexd.app.collector.activity.collector;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;

import java.util.List;

import cn.nexd.app.collector.R;
import cn.nexd.app.collector.activity.SelectBuildingActivity;
import cn.nexd.app.collector.activity.SettingActivity;
import cn.nexd.app.collector.application.NexdApplication;
import cn.nexd.app.collector.model.CollectConfig;
import cn.nexd.app.collector.presenter.collect.CollectPresenter;
import cn.nexd.app.collector.presenter.collect.MainContract;
import cn.nexd.app.collector.presenter.db.TableContract;
import cn.nexd.app.collector.util.ProgressUtil;
import cn.nexd.app.collector.util.ToastUtil;
import cn.nexd.app.collector.util.UMengUtil;
import cn.nexd.app.collector.widget.CollectorEndDialog;
import cn.nexd.app.collector.widget.WarningDialog;
import cn.nexd.app.collector.widget.sliding.OnSlidingListener;
import cn.nexd.app.collector.widget.sliding.SlidingView;
import cn.nexd.utils.framework.tools.SDCardUtil;


public class NexdCollectionActivity extends AppCompatActivity implements MainContract.View, OnSlidingListener, WarningDialog.OnDialogDismissListener {
    private String currentMallName, currentCollect;
    private String email;
    private String currentMallName_PY;
    private Toolbar tlBar;
    private TextView tvMallInfo;
    private SlidingView btnStart;
    private EditText etMallNo;
    private TextView environmentText;
    private WarningDialog warningDialog;
    private int initValue = 0;
    private TickerView stepView;
    private static final char[] NUMBER_LIST = TickerUtils.getDefaultNumberList();

    private boolean isStart = false;

    private MainContract.Presenter presenter;
    private boolean isShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();
        bindData();
        bindEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        UMengUtil.getInstance().onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        UMengUtil.getInstance().onPause(this);
    }

    private void bindEvent() {
        warningDialog.setOnDialogDismissListener(this);
        btnStart.setOnSlidingListener(this);
    }

    private void bindData() {
        tvMallInfo.setText(currentMallName);
        btnStart.setSlidingField(currentCollect);
    }

    public void initView() {
        warningDialog = new WarningDialog(this);
        warningDialog.setCanceledOnTouchOutside(false);
        tlBar = (Toolbar) findViewById(R.id.main_tl_mall);
        setSupportActionBar(tlBar);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        stepView = (TickerView) findViewById(R.id.main_step_size);
        stepView.setCharacterList(NUMBER_LIST);
        stepView.setAnimationDuration(500);
        stepView.setText(String.valueOf(initValue));
        tvMallInfo = (TextView) findViewById(R.id.main_mall_name);
        btnStart = (SlidingView) findViewById(R.id.collect_sliding_text);
        environmentText = (TextView) findViewById(R.id.main_environment_size);
        getSupportActionBar().setTitle("");
        etMallNo = (EditText) findViewById(R.id.main_input_mall_no);
        presenter = new CollectPresenter(this, this);
    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void startActivity() {

    }

    @Override
    public void printLog(String msg) {

    }

    private void initData() {
        Bundle mallBundle = getIntent().getExtras();
        if (mallBundle != null) {
            currentMallName = mallBundle.getString(TableContract.Building.COLUMN_BUILDING_NAME);
            email = mallBundle.getString(TableContract.User.COLUMN_NAME_USEREMAIL);
            currentMallName_PY = mallBundle.getString(TableContract.Building.COLUMN_BUILDING_NAME_PY);
        }
        List<CollectConfig> collectConfigs = NexdApplication.getInstance().getCollectConfigs();
        if (collectConfigs.size() == 2) {
            currentCollect = "混合";
        } else {
            currentCollect = collectConfigs.get(0).getCollectWay();
        }
    }

    @Override
    public void onBackPressed() {
        if (!isStart) {
            Intent intent = new Intent(this, SettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            setResult(SelectBuildingActivity.RESULT_CODE, intent);
            this.finish();
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, SettingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                setResult(SelectBuildingActivity.RESULT_CODE, intent);
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void dismiss() {
        etMallNo.setText("");
        etMallNo.requestFocus();
    }

    //往左滑到起始位置，准备开启采集

    @Override
    public void onLeft() {
        etMallNo.setEnabled(true);
        presenter.stopCollector();
        stepView.setText(String.valueOf(0));
        isStart = false;
    }

    //往右滑到终止位置，采集开启成功
    @Override
    public void onRight() {
        String[] available = SDCardUtil.getAvailableBlocks(SDCardUtil.getSDCardPath());

        if ("KB".equals(available[1]) || "MB".equals(available[1])) {
            showToast("存储空间不足，请清理 SDCard 内容");
            return;
        }

        if (!TextUtils.isEmpty(etMallNo.getText().toString())) {
            initValue = 0;
            etMallNo.setEnabled(false);
            isShow = false;
            presenter.startCollector(etMallNo.getText().toString(), currentMallName_PY, email);
            isStart = true;
        } else {
            ToastUtil.getInstance().showToast(this, "必须填写楼层");
            btnStart.reset();
        }
    }

    @Override
    public void updateEnvironment(String environment) {
        environmentText.setText(environment);
    }

    @Override
    public void updateSensorStep(String step) {
        stepView.setText(step);
    }

    @Override
    public void startCompassFile() {
        ProgressUtil.show(this, "提示", "正在压缩文件...", false);
    }

    @Override
    public void endCompassFile() {
        ProgressUtil.dismiss();
    }

    @Override
    public void pauseCollection(final int errorCode) {


        if (isShow) {
            return;
        }
        // 这里实现弹窗效果,并显示当前错误信息,错误码。
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CollectorEndDialog dialog = new CollectorEndDialog(NexdCollectionActivity.this);
                dialog.show();
                dialog.setDialogMsg(getString(R.string.collect_pause_msg) + "\n 错误代码: " + errorCode);
                dialog.setOnDialogClickListener(new CollectorEndDialog.onDialogClickListener() {
                    @Override
                    public void onSave() {
                        presenter.saveData();
                    }

                    @Override
                    public void onFail() {
                        presenter.cancelData();
                    }
                });
                isShow = true;
                btnStart.reset();

            }
        });
    }
}
